var app = getApp();
var modal = require('../../utils/modal');
var request = require('../../utils/request');
var utils = require('../../utils/utils');
var math = require('../../utils/math.js');
var storage = require('../../utils/storage');
var goTop = require('../widget/goTop/goTop');

var pageSetting = {
	data : {
		page:1,
        pageFlag:true,
		cartData : [],
		actSpecData : [],
		totalPrice : 0,
		max : [],
		min : [],
		checkAllStatus : true,
		flag : 1,
		noStockNum : 0,
		pageFlag : 1
	},
	dealSpecs: function(act_spec) {
		var tmp = act_spec.split(';');
		var specs = {}
		for(var i = 0; i < tmp.length; i++) {
			var item = tmp[i].split(',')
			specs[item[0]] = tmp[i]
		}

		return specs
	},
	onLoad : function(){
		modal.loading();
		var that = this;
		var cartData = that['data']['cartData'];
		var actSpecData = that['data']['actSpecData'];
		var totalPrice = that['data']['totalPrice'];
		var checkAllStatus = that['data']['checkAllStatus'];
		var min = that['data']['min'];
		var max = that['data']['max'];
		var data = {
			'dp:api:act:cartlist': {
				"page":1,
                "page_size":10
			}
		}
		request.post({
			path: '/wxapp_api/api'
		},data)
		.then(function(res){
			var checkNum = 0;
			var retData = res['dp:api:act:cartlist'];
			var cartDataTemp = retData['data']['cart_list'];
			var noStockNum = that.data.noStockNum;
			for(var i=0;i<cartDataTemp.length;i++){
				cartData.push(cartDataTemp[i]);
			}
			if(retData.ret != 0){
            	// modal.toast(retData.msg);
            	wx.navigateTo({
                    url: "../error/error"
                })
            	return false;
            }

            if(cartData.length < 10){
                that.setData({
                    flag:0
                });
            }
			for(var i=0;i<cartData.length;i++){
				if(!!cartData[i].exception) {
					noStockNum ++;
					cartData[i].selected = '2';
				}
				if(cartData[i].selected == '1'){
					checkNum ++;
				}
				var specs = that.dealSpecs(cartData[i].act_info.act_spec);
				var actSpec = specs[cartData[i].act_spec_id].split(',');
				if(cartData[i].selected == '1'){
					totalPrice += math.multiply(cartData[i].purchase_count,actSpec[2]);	
				}
				if(cartDataTemp[i].purchase_count >= cartDataTemp[i].act_stock){
					max.push('true');
				}else{
					max.push('false');
				}
				if(cartDataTemp[i].purchase_count == 1){
					min.push('true');
				}else{
					min.push('false');
				}
				actSpecData.push(actSpec);
			}
			totalPrice = parseFloat(totalPrice).toFixed(2);
			if(checkNum == cartData.length-noStockNum){
				checkAllStatus = true;
			}else{
				checkAllStatus = false;
			}
			that.setData({
				cartData: cartData,
	            lists : cartData,
	            actSpecData : actSpecData,
	            totalPrice : totalPrice,
	            max : max,
	            min : min,
	            checkAllStatus : checkAllStatus,
	            noStockNum : noStockNum
	        });
	        modal.hide();
		});
	},
	pullUpLoad : function(){
		var that= this;
        var page = that.data.page;
		var actSpecData = that['data']['actSpecData'];
		var totalPrice = parseFloat(that['data']['totalPrice']);
		var checkAllStatus = that['data']['checkAllStatus'];
        var pageFlag = that.data.pageFlag;
        var cartData = that.data.cartData;
        var noStockNum = that.data.noStockNum;
        var checkNum = 0;
        var max = that.data.max;
        var min = that.data.min;
        if(that.data.flag == 0){
            return false;
        }
        modal.loading();
        if(pageFlag){
            page ++;
            pageFlag = false;
            that.setData({
                page : page,
                pageFlag : pageFlag
            });
            request.post({
				path: '/wxapp_api/api'
			},{'dp:api:act:cartlist': {"page":page,"page_size":10}})
			.then(function(res){
				var retData = res['dp:api:act:cartlist'];
                if(retData.ret != 0){
                  // modal.toast(retData.msg);
                  wx.navigateTo({
                    url: "../error/error"
                	})
                  return false;
                }
                var cartDataTemp = retData['data']['cart_list'];
                pageFlag = true;
				for(var i=0;i<cartDataTemp.length;i++){
					if(!!cartDataTemp[i].exception) {
						noStockNum ++;
						cartDataTemp[i].selected = '2';
					}
					that.data.cartData.push(cartDataTemp[i]);
				}
				var cartData = that.data.cartData;
                if(cartDataTemp.length < 10){
                    that.setData({
                        flag:0
                    });
                }
        for(var i=0;i<cartData.length;i++){
					if(cartData[i].selected == '1'){
						checkNum ++;
					}
        }
        for(var i=0;i<cartDataTemp.length;i++){
        	var specs = that.dealSpecs(cartDataTemp[i].act_info.act_spec);
        	var actSpec = specs[cartDataTemp[i].act_spec_id].split(',');
					if(cartDataTemp[i].selected == '1'){
						totalPrice = add(math.multiply(cartDataTemp[i].purchase_count,actSpec[2]),totalPrice);	
					}
					if(cartDataTemp[i].purchase_count >= cartDataTemp[i].act_stock){
						max.push('true');
					}else{
						max.push('false');
					}
					if(cartDataTemp[i].purchase_count == 1){
						min.push('true');
					}else{
						min.push('false');
					}
					actSpecData.push(actSpec);
				}
				totalPrice = parseFloat(totalPrice).toFixed(2);
				if(checkNum == cartData.length-noStockNum){
					checkAllStatus = true;
				}else{
					checkAllStatus = false;
				}
				that.setData({
		            cartData : cartData,
		            lists : cartData,
		            actSpecData : actSpecData,
		            totalPrice : totalPrice,
		            max : max,
		            min : min,
		            checkAllStatus : checkAllStatus,
		            noStockNum : noStockNum,
		            pageFlag : pageFlag
		        });
		        modal.hide();
			});
        }
	},
	minusFun : function(e){
		var that = this;
		var cartData = that.data.cartData;
		var actSpecData = that.data.actSpecData;
		var totalPrice = parseFloat(that.data.totalPrice);
		var max = that.data.max;
		var pageFlag = that.data.pageFlag;
		var index = parseInt(e.currentTarget.dataset.index);
		var num = parseInt(cartData[index].purchase_count);
		var cart_id = cartData[index].id;
		app.globalData.cartCountState = true;
		app.globalData.cartNumState = true;
		app.globalData.cartDetailCount = true;
		if(num <= 1){
			wx.showModal({
				title: '提示',
				content: '是否将该商品从购物车移出？',
				confirmColor: '#000000',
				success: function(res) {
					if (res.confirm) {
						num = 0;
						request.post({
							path: '/wxapp_api/api'
						},{'dp:api:act:cartdelete':{'cart_id' : cart_id}})
						.then(function(res){
							var delData = res['dp:api:act:cartdelete'];
							if(cartData[index].selected == '1'){
								totalPrice = sub(actSpecData[index][2],totalPrice);
							}
							var tempData = [];
							var tempActData = [];
							var tempMax = [];

							if(delData.ret != 0){
			                	modal.toast(delData.msg);
			                	return false;
			                }
							if(delData.data){
								for(var i=0;i<cartData.length;i++){
									if(i != index){
										tempData.push(cartData[i]);
										tempActData.push(actSpecData[i]);
										tempMax.push(max[i]);
									}
								}
								that.setData({
									cartData : tempData,
									lists : tempData,
									actSpecData : tempActData,
									max : max,
									totalPrice : totalPrice
								});
							}
							return false;
						});			
					} else if (res.cancel) {
						return false;
				    }
				}
			})
			
		}

		if(num > 1){
			num --;
			var data = {
				'dp:api:act:cartsave' : {
					'purchase_count' : -1,
					'act_spec_id' : actSpecData[index][0],
					'act_spec' : actSpecData[index][1],
					'act_id' : cartData[index].act_id,
					'cart_id' : cart_id,
					'selected' : 1	
				}
			}
			if(pageFlag){
				pageFlag = false;
				that.setData({
					pageFlag : pageFlag
				})
				request.post({
					path: '/wxapp_api/api'
				},data)
				.then(function(res){
					pageFlag = true;
					var subCartData = res['dp:api:act:cartsave'];
					if(subCartData.ret != 0){
	                	modal.toast(subCartData.msg);
	                	return false;
	                } 
					if(subCartData.data){
						cartData[index].purchase_count = num;
						if(cartData[index].selected == '1'){
							totalPrice = sub(actSpecData[index][2],totalPrice);	
						}
						max[index] = 'false';
						that.setData({
							cartData : cartData,
							lists : cartData,
							totalPrice : totalPrice,
							max : max,
							pageFlag : pageFlag
						});
					}
				});	
			}
			
		}
	},
	plusFun : function(e){
		var that = this;
		var cartData = that.data.cartData;
		var pageFlag = that.data.pageFlag;
		var max = that.data.max;
		var actSpecData = that.data.actSpecData;
		var totalPrice = parseFloat(that.data.totalPrice);
		var index = parseInt(e.currentTarget.dataset.index);
		var num = parseInt(cartData[index].purchase_count);
		var cart_id = cartData[index].id;
		app.globalData.cartCountState = true;
		app.globalData.cartNumState = true;
		app.globalData.cartDetailCount = true;
		if(num < cartData[index].act_stock){
			num ++;
		}
		if(num >= cartData[index].act_stock){
			num = cartData[index].act_stock;
			max[index] = 'true';
			that.setData({
				max : max
			});
		}
		var data = {
			'dp:api:act:cartsave' : {
				'purchase_count' : 1,
				'act_spec_id' : actSpecData[index][0],
				'act_spec' : actSpecData[index][1],
				'act_id' : cartData[index].act_id,
				'cart_id' : cart_id,
				'selected' : 1	
			}
		}
		if(pageFlag){
			pageFlag = false;
			that.setData({
				pageFlag : pageFlag
			});
			request.post({
				path: '/wxapp_api/api'
			},data)
			.then(function(res){
				pageFlag = true;
				var addCartData = res['dp:api:act:cartsave'];
				if(addCartData.ret != 0){
	            	// modal.toast(addCartData.msg);
	            	that.setData({
	            		pageFlag : pageFlag
	            	});
	            	wx.navigateTo({
                        url: "../error/error"
                    })
	            	return false;
	            }
				if(addCartData.data){
					cartData[index].purchase_count = num;
					if(cartData[index].selected == '1'){
						totalPrice = (add(actSpecData[index][2],totalPrice)).toFixed(2);	
					}
					that.setData({
						cartData : cartData,
						lists : cartData,
						totalPrice : totalPrice,
						pageFlag : pageFlag
					});
				}
			});	
		}
		
	},
	changeCheckBoxFun : function(e){
		var that = this;
		var pageFlag =  that.data.pageFlag;
		var index = parseInt(e.currentTarget.dataset.index);
		var cartData = that.data.cartData;
		var totalPrice = parseFloat(that.data.totalPrice);
		var actSpecData = that.data.actSpecData;
		var checkAllStatus = that.data.checkAllStatus;
		var noStockNum = that.data.noStockNum;
		var checkNum = 0;
		var specs = that.dealSpecs(cartData[index].act_info.act_spec);
		var actSpec = specs[cartData[index].act_spec_id].split(',');
		if(pageFlag){
			pageFlag = false;
			that.setData({
				pageFlag : pageFlag
			});
			if(that.data.cartData[index].selected == '1'){
				cartData[index].selected = '0';
				var checkBoxData = {
					'car_id' : cartData[index].id,
					'select' : 0
				}
				totalPrice -= math.multiply(cartData[index].purchase_count,actSpec[2]);
			}else{
				cartData[index].selected = '1';
				var checkBoxData = {
					'car_id' : cartData[index].id,
					'select' : 1
				}
				totalPrice += math.multiply(cartData[index].purchase_count,actSpec[2]);
			}
			totalPrice = parseFloat(totalPrice).toFixed(2);
			for(var i=0;i<cartData.length;i++){
				if(cartData[i].selected == '1'){
					checkNum ++;
				}
			}
			if(checkNum == cartData.length-noStockNum){
				checkAllStatus = true;
			}else{
				checkAllStatus = false;
			}
			
			request.post({
				path : '/wxapp_api/api'
			},{'self:cart_api:cart:cartupdate':checkBoxData})
			.then(function(res){
				pageFlag = true;
				var checkData = res['self:cart_api:cart:cartupdate'];
				if(checkData.ret != 0){
	            	// modal.toast(checkData.msg);
	            	wx.navigateTo({
                        url: "../error/error"
                    })
	            	return false;
	            }
	            if(checkData.data){
		            that.setData({
						cartData : cartData,
						lists : cartData,
						totalPrice : totalPrice,
						checkAllStatus : checkAllStatus,
						pageFlag : pageFlag
					});
	            }
			});
	
		}
			},
	selectAllFun : function(e){
		var that = this;
		var cartData = that.data.cartData;
		var pageFlag = that.data.pageFlag;
		// var totalPrice = parseFloat(that.data.totalPrice);
		var totalPrice = 0;
		var checkAllStatus = that.data.checkAllStatus;
		var noStockNum = that.data.noStockNum;
		var cartIdData = [];
		var checkAllData = {};
		if(pageFlag){
			pageFlag = false;
			that.setData({
				pageFlag : pageFlag
			})
			if(checkAllStatus){
				for(var i=0;i<cartData.length;i++){
					if(!!cartData[i].exception){
						cartData[i].selected = '2';
						// cartIdData.push(cartData[i].id);
					}else{
						cartData[i].selected = '0';
						cartIdData.push(cartData[i].id);
					}
				}
				cartIdData = cartIdData.join(',');
				checkAllData = {
					'car_id' : cartIdData,
					'select' : 0
				}
			}else{
				for(var i=0;i<cartData.length;i++){
					if(!!cartData[i].exception){
						cartData[i].selected = '2';
						// cartIdData.push(cartData[i].id);
					}else{
						cartData[i].selected = '1';
						cartIdData.push(cartData[i].id);
					}
				}
				cartIdData = cartIdData.join(',');
				checkAllData = {
					'car_id' : cartIdData,
					'select' : 1
				}
			}
			checkAllStatus = !checkAllStatus;
			for(var i=0;i<cartData.length;i++){
				if(!cartData[i].exception){
					if(checkAllStatus && cartData[i].selected == '1'){
						var specs = that.dealSpecs(cartData[i].act_info.act_spec);
            var actSpec = specs[cartData[i].act_spec_id].split(',');
						totalPrice += math.multiply(cartData[i].purchase_count,actSpec[2]);
					}else{
						totalPrice = 0.00;
					}
				}
			}
			totalPrice = parseFloat(totalPrice).toFixed(2);
			request.post({
				path : '/wxapp_api/api'
			},{'self:cart_api:cart:cartupdate':checkAllData})
			.then(function(res){
				var checkData = res['self:cart_api:cart:cartupdate'];
				pageFlag = true;
				if(checkData.ret != 0){
	            	// modal.toast(checkData.msg);
	            	wx.navigateTo({
                        url: "../error/error"
                    })
	            	return false;
	            }
	            if(checkData.data){
		            that.setData({
						cartData : cartData,
						lists : cartData,
						totalPrice : totalPrice,
						checkAllStatus : checkAllStatus,
						pageFlag : pageFlag
					});
	            }
			})
		}
		
	},
	payTap : function(){
		var that = this;
		var cartData = that.data.cartData;
		var totalPrice = parseFloat(that.data.totalPrice);
		var actSpecData = that.data.actSpecData;
		var cartIdArr = [];
		var actIdArr = [];
		var typeArr = [];
		var numArr = [];
		if(totalPrice == 0){
			wx.showModal({
				title: '提示',
				content: '请先选择商品',
				showCancel : false,
				confirmColor: '#000000',
				success: function(res) {
				    // if (res.confirm) {
				    //   console.log('用户点击确定')
				    // }
				}
			})
			return false;
		}
		for(var i=0;i<cartData.length;i++){
			if(cartData[i].selected == '1'){
				cartIdArr.push(cartData[i].id);
				actIdArr.push(cartData[i].act_id);
				typeArr.push(actSpecData[i][0]);
				numArr.push(cartData[i].purchase_count);
			}
		}
		var cartIdStr = cartIdArr.join(',');
		var actIdStr = actIdArr.join(',');
		var typeStr = typeArr.join(',');
		var numStr = numArr.join(',');
		wx.redirectTo({
           url: '../order-detail/order-detail?cart_id='+cartIdStr+'&act_id='+actIdStr+'&type='+typeStr+'&num='+numStr
        })
	},
	changeLinkFn: function(e){
		var index = e.currentTarget.dataset.index;
		var cartData = this.data.cartData;
		var act_id = cartData[index].act_id;
		wx.redirectTo({
			url: '../detail/detail?act_id='+act_id
		});
	}
}
//加法运算
function add(arg1,arg2){
    var r1,r2,m;
    try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
    try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
    m=Math.pow(10,Math.max(r1,r2));
    return (arg1*m+arg2*m)/m;
}
//减法计算
function sub(arg1,arg2){
    var r1,r2,m,n;
    try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
    try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
    m=Math.pow(10,Math.max(r1,r2));
    //last modify by deeka
    //动态控制精度长度
    n=(r1>=r2)?r1:r2;
    return ((arg2*m-arg1*m)/m).toFixed(n);
}


utils.assign(pageSetting, goTop);
Page(pageSetting);